package com.vilinno.tlias.controller;

import com.vilinno.tlias.pojo.Result;
import com.vilinno.tlias.utils.AliyunOSSOperator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    private static final Logger log = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    @PostMapping
    public Result upload(MultipartFile file) throws Exception {

        log.info("上传文件信息是：{}",file.getOriginalFilename());

        String url=aliyunOSSOperator.upload(file.getBytes(),file.getOriginalFilename());
        log.info("文件上传到OSS，文件路径是：{}",url);

        return Result.success(url);

    }

    public Result localUpload(String name, Integer age, MultipartFile file) throws IOException {
        log.info("上传文件信息： {} {} {}",name,age,file);

        //获取文件名
        String originalFilename = file.getOriginalFilename();

        //获取拓展名，生成新文件名，防止文件重名
        String extension=originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName= UUID.randomUUID().toString()+extension;

        //本地存储
        file.transferTo(new File("D:/javaProject/tlias/src/main/resources/images/"+newFileName));

        return Result.success();
    }

}
